<template>
  <div class="query-editor">
    <div class="editor-container">
      <div class="editor-header">
        <h3>{{ $t('query.title') }} <el-tag size="small" :type="queryType === 'flux' ? 'warning' : 'success'">{{ queryType === 'flux' ? 'Flux' : 'InfluxQL' }}</el-tag></h3>
        <div class="editor-actions">
          <el-button type="primary" icon="el-icon-caret-right" @click="executeQuery" :loading="executing">
            {{ $t('query.execute') }}
          </el-button>
          <el-button icon="el-icon-document" @click="showHistory = true">
            {{ $t('query.queryHistory') }}
          </el-button>
          <el-button icon="el-icon-delete" @click="clearEditor">
            {{ $t('common.clear') }}
          </el-button>
        </div>
      </div>
      
      <div class="editor-wrapper">
        <codemirror
          v-model="queryText"
          :options="editorOptions"
          @ready="onEditorReady"
        />
      </div>
      
      <div class="results-container">
        <div class="results-header">
          <h4>{{ $t('query.results') }}</h4>
          <div v-if="queryResults.length > 0" class="result-actions">
            <span class="result-count">{{ queryResults.length }} {{ $t('query.rows') }}</span>
            <el-button size="mini" @click="exportResults">{{ $t('common.export') }}</el-button>
            <el-button size="mini" type="primary" @click="visualizeResults">{{ $t('explorer.visualize') }}</el-button>
          </div>
        </div>
        
        <div class="results-wrapper">
          <el-table
            v-if="queryResults.length > 0"
            :data="queryResults"
            height="100%"
            border
            stripe
          >
            <el-table-column
              v-for="(column, index) in resultColumns"
              :key="index"
              :prop="column"
              :label="column"
              :min-width="150"
            />
          </el-table>
          
          <el-empty v-else :description="$t('common.noData')" />
        </div>
      </div>
    </div>
    
    <el-drawer
      :title="$t('query.queryHistory')"
      :visible.sync="showHistory"
      direction="rtl"
      size="40%"
    >
      <div class="history-list">
        <el-timeline>
          <el-timeline-item
            v-for="item in queryHistory"
            :key="item.id"
            :timestamp="formatDate(item.timestamp)"
            placement="top"
          >
            <el-card>
              <pre class="history-query">{{ item.query }}</pre>
              <el-button size="mini" @click="loadHistoryQuery(item.query)">
                {{ $t('query.loadQuery') }}
              </el-button>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { codemirror } from 'vue-codemirror'
import Papa from 'papaparse'
import i18nMixin from '@/mixins/i18nMixin'

export default {
  name: 'QueryEditor',
  mixins: [i18nMixin],
  
  components: {
    codemirror
  },
  
  data() {
    return {
      queryText: '',
      defaultFluxQuery: 'from(bucket: "my-bucket")\n  |> range(start: -1h)\n  |> filter(fn: (r) => r._measurement == "cpu")',
      defaultInfluxQLQuery: 'SELECT * FROM cpu WHERE time > now() - 1h LIMIT 100',
      executing: false,
      showHistory: false,
      editor: null,
      editorOptions: {
        mode: 'text/x-sql',
        theme: 'material',
        lineNumbers: true,
        lineWrapping: true,
        autoCloseBrackets: true,
        matchBrackets: true,
        indentUnit: 2,
        tabSize: 2,
        extraKeys: {
          'Ctrl-Enter': () => this.executeQuery(),
          'Ctrl-Space': 'autocomplete'
        }
      }
    }
  },
  
  computed: {
    ...mapState(['queryResults', 'queryHistory', 'currentConnection']),
    
    queryType() {
      return this.currentConnection ? this.currentConnection.queryType || 'influxql' : 'influxql'
    },
    
    resultColumns() {
      if (this.queryResults.length === 0) return []
      return Object.keys(this.queryResults[0])
    }
  },
  
  mounted() {
    // Clear previous query results when entering the query editor
    this.$store.commit('SET_QUERY_RESULTS', [])
    
    this.loadQueryHistory()
    
    if (!this.currentConnection) {
      this.$message.warning('Please connect to a database first')
      this.$router.push('/connections')
    } else {
      // Only set default query if queryText is empty
      if (!this.queryText) {
        // Set default query based on query type
        if (this.queryType === 'flux') {
          this.queryText = this.defaultFluxQuery
        } else {
          this.queryText = this.defaultInfluxQLQuery
        }
      }
    }
  },
  
  watch: {
    currentConnection(newVal) {
      if (newVal) {
        // Only update default query if queryText is empty
        if (!this.queryText) {
          if (newVal.queryType === 'flux') {
            this.queryText = this.defaultFluxQuery
          } else {
            this.queryText = this.defaultInfluxQLQuery
          }
        }
      }
    }
  },
  
  methods: {
    ...mapActions(['executeQuery', 'loadQueryHistory']),
    
    onEditorReady(editor) {
      this.editor = editor
    },
    
    clearEditor() {
      this.queryText = ''
      this.editor && this.editor.focus()
    },
    
    async executeQuery() {
      if (!this.queryText.trim()) {
        this.$message.warning('Please enter a query')
        return
      }
      
      this.executing = true
      try {
        const result = await this.$store.dispatch('executeQuery', this.queryText)
        
        if (result.success) {
          this.$message.success('Query executed successfully')
        } else {
          this.$message.error('Query failed: ' + result.error)
        }
      } catch (error) {
        this.$message.error('Query execution failed: ' + error.message)
      } finally {
        this.executing = false
      }
    },
    
    loadHistoryQuery(query) {
      this.queryText = query
      this.showHistory = false
      this.editor && this.editor.focus()
    },
    
    formatDate(timestamp) {
      return new Date(timestamp).toLocaleString()
    },
    
    exportResults() {
      if (this.queryResults.length === 0) return
      
      this.$confirm('Select export format', 'Export Results', {
        distinguishCancelAndClose: true,
        confirmButtonText: 'CSV',
        cancelButtonText: 'JSON',
        type: 'info'
      }).then(() => {
        this.exportAsCSV()
      }).catch(action => {
        if (action === 'cancel') {
          this.exportAsJSON()
        }
      })
    },
    
    exportAsCSV() {
      const csv = Papa.unparse(this.queryResults)
      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      
      link.setAttribute('href', url)
      link.setAttribute('download', `query_results_${Date.now()}.csv`)
      link.style.visibility = 'hidden'
      
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$message.success('Results exported as CSV')
    },
    
    exportAsJSON() {
      const json = JSON.stringify(this.queryResults, null, 2)
      const blob = new Blob([json], { type: 'application/json' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      
      link.setAttribute('href', url)
      link.setAttribute('download', `query_results_${Date.now()}.json`)
      link.style.visibility = 'hidden'
      
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$message.success('Results exported as JSON')
    },
    
    visualizeResults() {
      if (this.queryResults.length === 0) {
        this.$message.warning('No results to visualize')
        return
      }
      
      // Format data for visualization
      const visualizationData = [{
        database: this.currentConnection.database || 'Query Results',
        measurement: 'Query Results',
        columns: this.resultColumns,
        data: this.queryResults,
        totalCount: this.queryResults.length,
        query: this.queryText
      }]
      
      // Store in vuex
      this.$store.commit('SET_QUERY_RESULTS', visualizationData)
      
      // Navigate to visualization page
      this.$router.push('/visualization')
      this.$message.success('Results sent to visualization')
    }
  }
}
</script>

<style scoped>
.query-editor {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f5f5f5;
  border-bottom: 1px solid #ddd;
}

.editor-header h3 {
  margin: 0;
}

.editor-wrapper {
  flex: 1;
  min-height: 300px;
  max-height: 60%;
  border-bottom: 1px solid #ddd;
  overflow: hidden;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.editor-wrapper >>> .CodeMirror {
  height: 100%;
  font-size: 14px;
}

.editor-wrapper >>> .CodeMirror-scroll {
  overflow-y: auto !important;
  overflow-x: auto !important;
}

.results-container {
  height: 40%;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #f5f5f5;
  border-bottom: 1px solid #ddd;
}

.results-header h4 {
  margin: 0;
}

.result-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.result-count {
  margin-right: 10px;
  color: #666;
}

.results-wrapper {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.history-list {
  padding: 20px;
}

.history-query {
  margin: 10px 0;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-all;
  font-family: 'Courier New', monospace;
  font-size: 12px;
}
</style>